package com.zuoshenge.sys.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zuoshenge.sys.dao.UserDao;
import com.zuoshenge.sys.dao.UserRecordDao;
import com.zuoshenge.sys.entity.User;
import com.zuoshenge.sys.entity.UserRecord;
import com.zuoshenge.sys.utils.JwtTokenUtil;
import com.zuoshenge.sys.utils.RedisUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;

@Service
public class UserDataService {

    @Resource
    private UserDao userDao;

    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private UserRecordDao userRecordDao;

    public int addUser(User user) {
        return userDao.insert(user);
    }

    public User loadUserByUsername(String username) {
        return userDao.loadUserByUserName(username);
    }

    public void setPoint(User user) {

    }

    public synchronized void punishment(User user) {
        String punishmentKry = jwtTokenUtil.punishmentKey(user.getUsername());
        redisUtil.setNx(punishmentKry, user.getUsername(), 10000L, TimeUnit.MILLISECONDS);
    }


    public synchronized int handleClick(User user, Integer points) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai")); // 使用"Asia/Shanghai"更精确
        UserRecord userRecord = new UserRecord(
            null,
            user.getUid(),
            points,
            sdf.format(new Date())
        );
        userRecordDao.insert(userRecord);
        if (user.getFreeCount() > 0) {
            user.setFreeCount(user.getFreeCount() - 1);
            user.setPoints(user.getPoints() + points);
            return userDao.clickUpdate(user);
        } else {
            if (user.getExtraCount() > 0) {
                user.setExtraCount(user.getExtraCount() - 1);
                user.setPoints(user.getPoints() + points);
                return userDao.clickUpdate(user);
            }
        }
        throw new RuntimeException("未更新用户抽奖后数据！");
    }

    public IPage<User> selectPage(String username, int pageNo, int pageSize) {
        // 使用 MyBatis-Plus 提供的 Page 类来构建分页对象
        Page<User> page = new Page<>(pageNo, pageSize);
        // 假设 userMapper 继承了 BaseMapper<User>
        return userDao.selectPage(page, new QueryWrapper<User>().like("username", username));
    }
}
